'use strict';

const Service = require('egg').Service;

class UserRoleService extends Service {


  // 获取列表
  async getList(pageNum, pageSize) {
    const { app } = this;
    try {
      const offset = (pageNum - 1) * pageSize;
      const { count, rows } = await app.model.UserRole.findAndCountAll({
        offset,
        limit: pageSize * 1,
        include: [
          {
            model: app.model.Role,
            attributes: {
              exclude: [ 'createdAt', 'updatedAt', 'deletedAt' ],
            },
            where: {
              // name: { [ Op.like ]: '%stri%' },
            },
          },
        ],
      });
      return {
        pageNum,
        pageSize,
        total: count,
        list: rows,
      };
    } catch (error) {
      console.error(error);
      return null;
    }
  }

  // 根据id获取信息
  async findOne(id) {
    return await this.app.model.UserRole.findOne({ where: { id } });
  }

  // 删除
  async del(payload) {
    const { app } = this;
    return await app.model.UserRole.destroy({ where: { id: payload.ids }, force: true });
  }


  // 新增
  async create(payload) {
    const { app } = this;
    return await app.model.UserRole.create(payload);
  }

  // 修改
  async updated(id, payload) {
    const { app } = this;
    return await app.model.UserRole.update(payload, { where: { id } });
  }

  // 单用户批量添加多角色
  async bulkCreateRole(payload) {
    const { app } = this;
    payload = payload.role_ids.map(e => {
      return { user_id: payload.user_id, role_id: e };
    });
    console.log('payload', payload);
    return await app.model.UserRole.bulkCreate(payload);
  }


}

module.exports = UserRoleService;
